from flask import (
    jsonify,
    request,
    Blueprint
)
from config.config import Base
from service import MongoService

name = 'books'
books_route = Blueprint(name, __name__, template_folder=Base.templateUrl)

cms_service = MongoService('book')


# http://weixin.pbani.com/test/hello

@books_route.route('/queryCategoryList', methods=["GET"])
def query_category_list():
    # db.books.aggregate([{$group: {_id: '$majorCate'}}])
    res1 = cms_service.aggregate('books', [{"$group": {"_id": '$majorCate'}}])

    category_list = []
    for item in res1:
        category_list.append({
            "_id": item['_id']
        })
    response = jsonify({
        "categoryList": category_list
    })
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response


@books_route.route('/Test', methods=["GET"])
def test():
    response = jsonify({
        "ip": "dfad"
    })
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response


@books_route.route('/GetBooksByCategory', methods=["GET", "POST"])
def get_books_by_category():
    category = request.args.get("category", '传记名著')
    # db.getCollection('books').find({"majorCate": "传记名著"})

    res1 = cms_service.find('books', {
        'majorCate': category
    })

    book_list = []
    for item in res1:
        book_list.append(item)
    response = jsonify({
        "book_list": book_list
    })
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
